package cn.openea.perpartner.componet.web.controller;


import cn.openea.perpartner.common.core.config.SystemConfig;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.utils.file.FileUploadUtils;
import cn.openea.perpartner.common.core.utils.file.FileUtils;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.componet.util.CosUpload;
import cn.openea.perpartner.componet.web.entity.Attachment;
import cn.openea.perpartner.componet.web.entity.dto.AttachDto;
import cn.openea.perpartner.componet.web.service.IAttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Api(tags = "附件管理")
@RestController
@RequestMapping("/attachment")
public class AttachmentController extends BaseController {

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private CosUpload cosUpload;
    private static final String FILE_DELIMETER = ",";

    @ApiOperation("DB-附件列表")
    @PostMapping("/list")
    public TableDataInfo selectList(@RequestBody AttachDto dto) {
        startPage();
        List<Attachment> list = this.attachmentService.selectList(dto);
        return getDataTable(list);
    }

    @ApiOperation("DB-附件详情")
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return success(this.attachmentService.getById(id));
    }

    @ApiOperation("DB-保存附件")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Attachment attachment) {
        return toAjax(this.attachmentService.add(attachment));
    }

    @ApiOperation("DB-修改附件")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Attachment attachment) {
        return toAjax(this.attachmentService.updateById(attachment));
    }

    @ApiOperation("DB-删除附件")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody List<String> idList) {
        return toAjax(this.attachmentService.removeBatchByIds(idList));
    }

    @ApiOperation(value = "COS-文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = SystemConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            File localFile = new File(filePath + "/" + fileName);
            String url = cosUpload.uploadFile(localFile, false);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("suffix", Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".")));
            FileUtils.emptyDir(filePath);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "COS-多文件上传")
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) {
        try {
            // 上传文件路径
            String filePath = SystemConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                File localFile = new File(filePath + "/" + fileName);
                String url = cosUpload.uploadFile(localFile, false);
                urls.add(url);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            FileUtils.emptyDir(filePath);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}

